package com.wj.service.communication;

import com.alibaba.fastjson.JSON;
import com.wj.constant.CommonConstant;
import com.wj.vo.JwtToken;
import com.wj.vo.UsernameAndPassword;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 使用 Ribbon 实现微服务通信
 */
@Slf4j
@Service
public class UseRibbonService {

    private final RestTemplate restTemplate;

    public UseRibbonService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }


    /**
     *  通过 Ribbon 调用 Authority 服务获取 Token
     */
    public JwtToken getTokenFromAuthorityServiceByRibbon(UsernameAndPassword usernameAndPassword){
        // url 中的 ip 和端口换成了服务名称
        String requestUrl = String.format("http://%s/wj-code-authority-center/authority/token",
                CommonConstant.AUTHORITY_CENTER_SERVICE_ID);
        log.info("login request url and body: [{}], [{}]", requestUrl, JSON.toJSONString(usernameAndPassword));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 这里一定要用自己注入的 RestTemplate
        return restTemplate.postForObject(
                requestUrl,
                new HttpEntity<>(JSON.toJSONString(usernameAndPassword),headers),
                JwtToken.class
        );
    }

}
